package com.example.study.page.view

import android.content.Context
import android.graphics.Canvas
import android.graphics.Path
import android.graphics.RectF
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.graphics.toRect
import com.example.study.R

/**
 * Created by lijinxi on 2024/2/28
 * @Description:
 */
class RadiusCornerConstraintLayout(context: Context, attrs: AttributeSet?) :
    ConstraintLayout(context, attrs) {
    private var radius: Float = 0.0f
    private var clipPath = Path()
    private var background: Drawable? = null

    // 获取自定义属性
    init {
        val typedArray =
            context.obtainStyledAttributes(attrs, R.styleable.RadiusCornerConstraintLayout)
        radius = typedArray.getDimension(
            R.styleable.RadiusCornerConstraintLayout_radius,
            20f * context.resources.displayMetrics.density
        )
        typedArray.recycle()
    }

    override fun setBackground(background: Drawable?) {
        this.background = background
    }

    override fun dispatchDraw(canvas: Canvas) {
        // 保存画布状态
        val saveCount = canvas.save()
        clipPath.reset()
        val rect = RectF(0f, 0f, width.toFloat(), height.toFloat())
        clipPath.addRoundRect(rect, radius, radius, Path.Direction.CW)
        canvas.clipPath(clipPath)
        // 绘制圆角背景
        background?.apply {
            bounds = rect.toRect()
            draw(canvas)
        }
        super.dispatchDraw(canvas)
        // 恢复画布状态
        canvas.restoreToCount(saveCount)
    }
}